# -*- coding: utf-8 -*-

import json
import os
import sys

class Settings:
    def __init__(self, config_file="config/config.json"):
        # 获取正确的配置文件路径，兼容打包环境
        if not os.path.isabs(config_file):
            # 相对路径，需要根据运行环境确定基础路径
            if getattr(sys, 'frozen', False):
                # 打包环境
                if hasattr(sys, 'executable'):
                    base_path = os.path.dirname(sys.executable)
                else:
                    base_path = os.getcwd()
            else:
                # 开发环境
                base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            
            self.config_file = os.path.join(base_path, config_file)
        else:
            self.config_file = config_file
            
        # 确保config目录存在
        config_dir = os.path.dirname(self.config_file)
        if not os.path.exists(config_dir):
            os.makedirs(config_dir)
        self.config = {
            "connections": [],
            "groups": [],
            "default_upload_dir": "/tmp",
            "default_download_dir": "download",
            "default_upload_files": [],
            "default_download_files": []
        }
        self.load_config()
        
    def load_config(self):
        """加载配置文件"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    loaded_config = json.load(f)
                    
                # 确保所有必需的字段都存在
                required_fields = {
                    "connections": [],
                    "groups": [],
                    "default_upload_dir": "/tmp",
                    "default_download_dir": "download",
                    "default_upload_files": [],
                    "default_download_files": []
                }
                
                # 合并加载的配置和必需字段，确保不会丢失任何字段
                for key, default_value in required_fields.items():
                    if key not in loaded_config:
                        loaded_config[key] = default_value
                        
                self.config = loaded_config
            except Exception as e:
                print(f"加载配置文件失败: {e}")
        else:
            self.save_config()
            
    def save_config(self):
        """保存配置文件"""
        try:
            # 确保目录存在
            config_dir = os.path.dirname(self.config_file)
            if not os.path.exists(config_dir):
                os.makedirs(config_dir)
                
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存配置文件失败: {e}")
            
    def add_group(self, name):
        """添加分组"""
        group = {
            "id": len(self.config["groups"]),
            "name": name,
            "connections": []
        }
        self.config["groups"].append(group)
        self.save_config()
        return group
        
    def add_connection(self, group_id, name, host, port, username, password=None, key_file=None):
        """添加连接"""
        # 找到最大的连接ID，然后加1作为新连接的ID
        max_id = -1
        for conn in self.config["connections"]:
            if conn["id"] > max_id:
                max_id = conn["id"]
        new_id = max_id + 1
        
        connection = {
            "id": new_id,
            "name": name,
            "host": host,
            "port": port,
            "username": username,
            "password": password,
            "key_file": key_file
        }
        self.config["connections"].append(connection)
        
        # 添加到分组
        for group in self.config["groups"]:
            if group["id"] == group_id:
                group["connections"].append(connection["id"])
                break
                
        self.save_config()
        return connection
        
    def remove_group(self, group_id):
        """删除分组"""
        # 先删除分组中的所有连接
        group_to_remove = None
        for group in self.config["groups"]:
            if group["id"] == group_id:
                group_to_remove = group
                break
                
        if group_to_remove:
            # 删除该分组下的所有连接
            for conn_id in group_to_remove["connections"]:
                self.config["connections"] = [c for c in self.config["connections"] if c["id"] != conn_id]
            # 删除分组
            self.config["groups"] = [g for g in self.config["groups"] if g["id"] != group_id]
            
        self.save_config()
        
    def remove_connection(self, connection_id):
        """删除连接"""
        self.config["connections"] = [c for c in self.config["connections"] if c["id"] != connection_id]
        for group in self.config["groups"]:
            group["connections"] = [cid for cid in group["connections"] if cid != connection_id]
        self.save_config()
        
    def update_connection(self, connection_id, name, host, port, username, password=None, key_file=None):
        """更新连接"""
        for connection in self.config["connections"]:
            if connection["id"] == connection_id:
                connection["name"] = name
                connection["host"] = host
                connection["port"] = port
                connection["username"] = username
                connection["password"] = password
                connection["key_file"] = key_file
                break
        self.save_config()
        
    def update_group(self, group_id, name):
        """更新分组"""
        for group in self.config["groups"]:
            if group["id"] == group_id:
                group["name"] = name
                break
        self.save_config()
        
    def get_groups(self):
        """获取所有分组"""
        return self.config["groups"]
        
    def get_connections(self):
        """获取所有连接"""
        return self.config["connections"]
        
    def get_connections_by_group(self, group_id):
        """根据分组ID获取连接"""
        connection_map = {c["id"]: c for c in self.config["connections"]}
        for group in self.config["groups"]:
            if group["id"] == group_id:
                return [connection_map[cid] for cid in group["connections"] if cid in connection_map]
        return []
        
    def set_default_upload_dir(self, directory):
        """设置默认上传目录"""
        self.config["default_upload_dir"] = directory
        self.save_config()
        
    def get_default_upload_dir(self):
        """获取默认上传目录"""
        return self.config.get("default_upload_dir", "/tmp")
        
    def set_default_download_dir(self, directory):
        """设置默认下载目录"""
        self.config["default_download_dir"] = directory
        self.save_config()
        
    def get_default_download_dir(self):
        """获取默认下载目录"""
        return self.config.get("default_download_dir", "download")
        
    def set_default_upload_files(self, files):
        """设置默认上传文件列表"""
        self.config["default_upload_files"] = files
        self.save_config()
        
    def get_default_upload_files(self):
        """获取默认上传文件列表"""
        return self.config.get("default_upload_files", [])
        
    def set_default_download_files(self, files):
        """设置默认下载文件列表"""
        self.config["default_download_files"] = files
        self.save_config()
        
    def get_default_download_files(self):
        """获取默认下载文件列表"""
        return self.config.get("default_download_files", [])